package process

import (
	"bufio"
	"fmt"
	"github.com/docker/docker/pkg/reexec"
	"io"
	"log"
	"os"
	"os/exec"
	"syscall"
	"time"
)

func fork() {
	const url = "www.bilibili.com"
	cmd1 := exec.Command("ping", url)
	ppReader, err := cmd1.StdoutPipe()
	defer ppReader.Close()
	var bufReader = bufio.NewReader(ppReader)
	if err != nil {
		fmt.Printf("create cmd stdoutpipe failed,error:%s\n", err)
		os.Exit(1)
	}
	err = cmd1.Start()
	if err != nil {
		fmt.Printf("cannot start cmd1,error:%s\n", err)
		os.Exit(1)
	}
	go func() {
		var buffer = make([]byte, 1<<12)
		for {
			n, err := bufReader.Read(buffer)
			if err != nil {
				if err == io.EOF {
					fmt.Printf("pipi has Closed\n")
					break
				} else {
					fmt.Println("Read content failed")
				}
			}
			fmt.Print(string(buffer[:n]))
		}
	}()
	time.Sleep(10 * time.Second)
	err = stopProcess(cmd1)
	if err != nil {
		fmt.Printf("stop child process failed,error:%s", err)
		os.Exit(1)
	}
	cmd1.Wait()
	time.Sleep(1 * time.Second)
}

func stopProcess(cmd *exec.Cmd) error {
	pro, err := os.FindProcess(cmd.Process.Pid)
	if err != nil {
		return err
	}
	err = pro.Signal(syscall.SIGINT)
	if err != nil {
		return err
	}
	fmt.Printf("exit child process pid:%d\tsuccess\n", cmd.Process.Pid)
	return nil
}

func creatChildProcess() {
	log.Println("main process")
	cmd := reexec.Command("childProcess")
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Start(); err != nil {
		log.Panicf("failed to run command: %s", err)
	}
	pid := cmd.Process.Pid
	log.Println("child pid:", pid)
	time.Sleep(50 * time.Millisecond)
	err := stopProcess(cmd)
	if err != nil {
		fmt.Printf("stop child process failed,error:%s", err)
		os.Exit(1)
	}
	cmd.Wait()

	log.Println("main exit")
}

func childProcess() {
	ticker := time.NewTicker(20 * time.Millisecond)
	for range ticker.C {
		log.Println("child process")
	}
}

func init() {
	log.Printf("init start, os.Args = %+v\n", os.Args)
	reexec.Register("childProcess", childProcess)
	if reexec.Init() {
		os.Exit(0)
	}
}
